package cn.edu.nju.sharing;

import cn.edu.nju.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity{
	private StartUpProvider provider;
	private EditText usernameInput;
	private EditText passwordInput;
	private TextView registerText;
	private TextView errorText;
	private RegisterClickableSpan registerSpan;	
	private Button loginButton;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login);
		provider = StartUpProvider.getInstance(this);
		
		// init widget
		usernameInput = (EditText)findViewById(R.id.user_name_input);
		passwordInput = (EditText)findViewById(R.id.password_input);
		errorText = (TextView)findViewById(R.id.error_message);
		initRegisterText();
		initLoginButton();
	}
	
	private void initLoginButton(){
		loginButton = (Button)findViewById(R.id.login_button);
		loginButton.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				// collect username and password
				String username = usernameInput.getText().toString();
				String password = passwordInput.getText().toString();
				
				if(provider.login(username, password) == -1){
					errorText.setText(R.string.login_error);
				}
				else{
					finish();
				}
			}
		});
	}
	
	private void initRegisterText(){
		registerText = (TextView)findViewById(R.id.register_entry_text);
		registerSpan = new RegisterClickableSpan(this) {
			@Override
			public void onClick(View widget) {
				// go to register activity
				Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
				startActivity(intent);
			}
		};
		
		registerText.setMovementMethod(LinkMovementMethod.getInstance());
		Spannable spans = (Spannable)registerText.getText();
		spans.setSpan(registerSpan, 9, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	}
}
